package com.zatech.cgnci.project.base.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.zatech.cgnci.project.base.utils.SM4Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfig {

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String encryptedPassword; // 加密后的密码

    @Value("${spring.datasource.druid.connection-properties.config.decrypt.key}")
    private String sm4Key; // SM4 密钥

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);

        // 解密密码
        try {
            String password = SM4Util.decryptBase64(sm4Key, encryptedPassword.replace("ENC(", "").replace(")", ""));
            dataSource.setPassword(password);
        } catch (Exception e) {
            throw new RuntimeException("Failed to decrypt password", e);
        }

        // 其他 Druid 配置
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(5);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(60000);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);

        return dataSource;
    }
}